package no.ntnu.item.ttm4115.termproject.teacheragent.gui;

import java.awt.event.ActionEvent;
import java.util.Vector;

import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListModel;

import com.thoughtworks.xstream.XStream;

import no.ntnu.item.ttm4115.termproject.AddGroupFromGUI;
import no.ntnu.item.ttm4115.termproject.extrasagent.Group;
import no.ntnu.item.ttm4115.termproject.extrasagent.Player;
import no.tellu.common.actorframe.ActorSM;
import no.tellu.common.javaframe.ActorAddress;

/*
 * NewGroup.java
 *
 * Created on 8. juli 2008, 09:23
 */



/**
 *
 * @author  bruker
 */
@SuppressWarnings("serial")
public class NewGroup extends javax.swing.JPanel {

    private TeacherGUI gui;
	private ActorSM asm;
	private String selectedLeader;
	/** Creates new form NewGroup */
    public NewGroup(TeacherGUI gui,ActorSM asm) {
        gui.setStartPanel(this);
        this.gui = gui;
        this.asm = asm;
    	initComponents();
    	javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this.gui.getContentPane());
        this.gui.getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(this, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(this, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        addNewGroupLabel = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        groupNameLabel = new javax.swing.JLabel();
        groupNameTextField = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        addedPlayersList = new javax.swing.JList();
        jScrollPane2 = new javax.swing.JScrollPane();
        availablePlayersList = new javax.swing.JList();
        groupRightsLabel = new javax.swing.JLabel();
        imCheckBox = new javax.swing.JCheckBox();
        chatCheckBox = new javax.swing.JCheckBox();
        discussionCheckBox = new javax.swing.JCheckBox();
        addedPlayersLabel = new javax.swing.JLabel();
        availablePlayersLabel = new javax.swing.JLabel();
        addGroupButton = new javax.swing.JButton();
        addPlayersButton = new javax.swing.JButton();
        removePlayersButton = new javax.swing.JButton();
        jScrollPane3 = new javax.swing.JScrollPane();
        addedGamesList = new javax.swing.JList();
        jScrollPane4 = new javax.swing.JScrollPane();
        availableGamesList = new javax.swing.JList();
        addedGamesLabel = new javax.swing.JLabel();
        availableGamesLabel = new javax.swing.JLabel();
        addGameButton = new javax.swing.JButton();
        removeGameButton = new javax.swing.JButton();
        addedGamesListModel = new DefaultListModel();
        addedPlayersListModel = new DefaultListModel();
        availableGamesListModel = new DefaultListModel();
        availablePlayersListModel = new DefaultListModel();
        groupLeaderLabel = new javax.swing.JLabel();
        groupLeaderComboBox = new javax.swing.JComboBox();
        selectLeaderButton = new javax.swing.JButton();
        groupLeaderComboModel = new DefaultComboBoxModel();

        addNewGroupLabel.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        addNewGroupLabel.setText("Add New Group");

        groupNameLabel.setText("Group Name");

        addedPlayersList.setModel(getAddedPlayersListModel());
        jScrollPane1.setViewportView(addedPlayersList);
       
        fillPlayersList(getAvailablePlayersListModel());
        availablePlayersList.setModel(getAvailablePlayersListModel());
        jScrollPane2.setViewportView(availablePlayersList);

        groupRightsLabel.setText("Group Rights :");

        imCheckBox.setText("IM");

        chatCheckBox.setText("Chat");
      

        discussionCheckBox.setText("Discussion");

        addedPlayersLabel.setText("Added Players");

        availablePlayersLabel.setText("Available Players");

        addGroupButton.setText("Add Group");
        addGroupButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addGroupButtonActionPerformed(evt);
            }
        });

        addPlayersButton.setText("Add");
        addPlayersButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	addPlayersButtonActionPerformed(evt);
            }
        });

        removePlayersButton.setText("Remove");
        removePlayersButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	removePlayersButtonActionPerformed(evt);
            }
        });

        jScrollPane3.setViewportView(addedGamesList);
        fillGamesList(getAvailableGamesListModel());
        availableGamesList.setModel(getAvailableGamesListModel());
        jScrollPane4.setViewportView(availableGamesList);

        addedGamesLabel.setText("Added Games");

        availableGamesLabel.setText("Available Games");

        addGameButton.setText("Add Game");
        addGameButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addGameButtonActionPerformed(evt);
            }
        });

        removeGameButton.setText("Remove");
        removeGameButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                removeGameButtonActionPerformed(evt);
            }
        });
        
        groupLeaderLabel.setText("Group Leader");
        
        fillGroupLeaderComboBox(groupLeaderComboModel);
        groupLeaderComboBox.setModel(groupLeaderComboModel);
        
        selectLeaderButton.setText("Select");
        selectLeaderButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                selectLeaderButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(addNewGroupLabel)
                .addContainerGap(444, Short.MAX_VALUE))
            .addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 550, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(groupNameLabel)
                .addGap(18, 18, 18)
                .addComponent(groupNameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(38, 38, 38)
                .addComponent(groupRightsLabel)
                .addGap(18, 18, 18)
                .addComponent(imCheckBox)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(chatCheckBox)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(discussionCheckBox)
                .addContainerGap(66, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(addedPlayersLabel)
                            .addComponent(removePlayersButton))
                        .addGap(37, 37, 37)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(availablePlayersLabel)
                            .addComponent(addPlayersButton))
                        .addGap(52, 52, 52)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(removeGameButton)
                            .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(addedGamesLabel))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 26, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(availableGamesLabel)
                            .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(addGameButton))
                        .addGap(24, 24, 24))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(addGroupButton)
                        .addContainerGap(457, Short.MAX_VALUE))))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(groupLeaderLabel)
                .addGap(18, 18, 18)
                .addComponent(groupLeaderComboBox, 0, 117, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addComponent(selectLeaderButton)
                .addGap(261, 261, 261))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(addNewGroupLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(groupNameLabel)
                    .addComponent(groupNameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(groupRightsLabel)
                    .addComponent(imCheckBox)
                    .addComponent(chatCheckBox)
                    .addComponent(discussionCheckBox))
                .addGap(24, 24, 24)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(addedPlayersLabel)
                    .addComponent(availablePlayersLabel)
                    .addComponent(addedGamesLabel)
                    .addComponent(availableGamesLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 112, Short.MAX_VALUE)
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 112, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 112, Short.MAX_VALUE)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 112, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(removePlayersButton)
                    .addComponent(addPlayersButton)
                    .addComponent(addGameButton)
                    .addComponent(removeGameButton))
                .addGap(27, 27, 27)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(groupLeaderLabel)
                    .addComponent(groupLeaderComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(selectLeaderButton))
                .addGap(18, 18, 18)
                .addComponent(addGroupButton)
                .addGap(47, 47, 47))
        );
    }// </editor-fold>
    
    private void selectLeaderButtonActionPerformed(ActionEvent evt) {
    	selectedLeader = (String) groupLeaderComboBox.getModel().getSelectedItem();
		
	}

	private void fillPlayersList(DefaultListModel model){
    	model.removeAllElements();
    	for (int i = 0; i < gui.getPlayers().size(); i++) {
			String player = (String)gui.getPlayers().elementAt(i).getUserName();
			model.addElement(player);
		}
    }
    private DefaultListModel getAvailablePlayersListModel(){
    	return availablePlayersListModel;
    }
    private void fillGamesList(DefaultListModel model){
    	model.removeAllElements();
    	
    }
    private DefaultListModel getAddedPlayersListModel(){
    	return addedPlayersListModel;
    }
    private DefaultListModel getAddedGamesListModel() {
    	return addedGamesListModel;
    }
    private DefaultListModel getAvailableGamesListModel(){
    	return availableGamesListModel;
    }
    private void fillAddedPlayersList(Object[] players){
    	if(players != null){
			for(int i=0; i<players.length;i++){
				if(checkAddedPlayersList((String) players[i])){
					addedPlayersListModel.addElement((players[i]));
				}
			}
		}
    	addedPlayersList.repaint();
    }
    private boolean checkAddedPlayersList(String player){
		boolean booleanValue = true;
		for(int i=0; i<getAddedPlayersListModel().getSize();i++){
			if(getAddedPlayersListModel().getElementAt(i)==player){
				booleanValue = false;
				break;
			}
		}
		return booleanValue;
	}
    private void fillGroupLeaderComboBox(DefaultComboBoxModel model){
    	model.removeAllElements();
    	for (int i = 0; i < addedPlayersListModel.getSize(); i++) {
			model.addElement(addedPlayersListModel.get(i));
		}
    }
    private void removePlayersFromAddedList(Object[] players){
    	if(players != null){
    		for (int i = 0; i < players.length; i++) {
				for (int j = 0; j < getAddedPlayersListModel().size(); j++) {
					if(players[i].equals(getAddedPlayersListModel().elementAt(j))){
						getAddedPlayersListModel().remove(j);
					}
				}
			}
    	}
    }

   

    private void removePlayersButtonActionPerformed(java.awt.event.ActionEvent evt) {
    	Object[] playersToBeRemoved =  addedPlayersList.getSelectedValues();
		removePlayersFromAddedList(playersToBeRemoved);
		fillGroupLeaderComboBox(groupLeaderComboModel);
    }

    private void addPlayersButtonActionPerformed(java.awt.event.ActionEvent evt) {
    	Object[] playersToBeAdded =  availablePlayersList.getSelectedValues();
    	System.out.println(playersToBeAdded[0]);
		fillAddedPlayersList(playersToBeAdded);
		fillGroupLeaderComboBox(groupLeaderComboModel);
    }

    private void removeGameButtonActionPerformed(java.awt.event.ActionEvent evt) {
    	// TODO add your handling code here:
    }

    private void addGameButtonActionPerformed(java.awt.event.ActionEvent evt) {
    	// TODO add your handling code here:
    }

    private void addGroupButtonActionPerformed(java.awt.event.ActionEvent evt) {
    	Vector<String> groupPlayersVector = new Vector<String>();
		for(int i=0; i<getAddedPlayersListModel().getSize();i++){
			groupPlayersVector.add((String) getAddedPlayersListModel().getElementAt(i));
		}
		Group newGroup = new Group();
		newGroup.setChat(chatCheckBox.isSelected());
		newGroup.setDiscussion(discussionCheckBox.isSelected());
		newGroup.setIm(imCheckBox.isSelected());
		newGroup.setGroupName(groupNameTextField.getText());
		newGroup.setPlayers(mergeStringAndPlayer(groupPlayersVector));
		newGroup.setLeader(selectedLeader);
		XStream xstream = new XStream();
		xstream.setClassLoader(new Group().getClass().getClassLoader());
		//xstream.setClassLoader(new Player().getClass().getClassLoader());
		xstream.alias("group", Group.class);
		xstream.alias("player",Player.class);
		xstream.setMode(XStream.XPATH_ABSOLUTE_REFERENCES);
		
		String group = xstream.toXML(newGroup);
		
		asm.sendMessage(new AddGroupFromGUI(group),new ActorAddress("/classManager","ClassManager"));
		gui.getGroups().add(newGroup);
		resetScheme();
	}
    
    private void resetScheme(){
    	groupNameTextField.setText("");
    	getAddedPlayersListModel().removeAllElements();
    	getAddedGamesListModel().removeAllElements();
    	addedGamesList.repaint();
    	addedPlayersList.repaint();
    }
    private Vector<Player> mergeStringAndPlayer(Vector<String> stringVector){
		Vector<Player> finalPlayerVector = new Vector<Player>();
		for (int i = 0; i < stringVector.size(); i++) {
			for (int j = 0; j < gui.getPlayers().size(); j++) {
				if(stringVector.elementAt(i).toString().equals(gui.getPlayers().elementAt(j).getUserName().toString())){
					finalPlayerVector.add(gui.getPlayers().elementAt(j));
				}
			}
		}	
		return finalPlayerVector; 
	} 


    // Variables declaration - do not modify
    private javax.swing.JButton addGameButton;
    private javax.swing.JButton addGroupButton;
    private javax.swing.JLabel addNewGroupLabel;
    private javax.swing.JLabel addedGamesLabel;
    private javax.swing.JList addedGamesList;
    private javax.swing.JLabel addedPlayersLabel;
    private javax.swing.JList addedPlayersList;
    private javax.swing.JLabel availableGamesLabel;
    private javax.swing.JList availableGamesList;
    private javax.swing.JLabel availablePlayersLabel;
    private javax.swing.JList availablePlayersList;
    private javax.swing.JCheckBox chatCheckBox;
    private javax.swing.JCheckBox discussionCheckBox;
    private javax.swing.JLabel groupNameLabel;
    private javax.swing.JTextField groupNameTextField;
    private javax.swing.JLabel groupRightsLabel;
    private javax.swing.JCheckBox imCheckBox;
    private javax.swing.JButton addPlayersButton;
    private javax.swing.JButton removePlayersButton;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JButton removeGameButton;
    private javax.swing.DefaultListModel availablePlayersListModel;
    private javax.swing.DefaultListModel addedPlayersListModel;
    private javax.swing.DefaultListModel availableGamesListModel;
    private javax.swing.DefaultListModel addedGamesListModel;
    private javax.swing.JButton selectLeaderButton;
    private javax.swing.JLabel groupLeaderLabel;
    private javax.swing.JComboBox groupLeaderComboBox;
    private javax.swing.DefaultComboBoxModel groupLeaderComboModel;
    // End of variables declaration

}
